<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>放大镜</title>
    <style>
        #fdj {
            position: relative;
            width: 450px;
            height: 450px;
        }
        #fdj img{
            width: 450px;
            height: 450px;
        }
        #fdj .mengban {
            position: absolute;
            display: none;
            width: 225px;
            height: 225px;
            background-color: yellow;
            opacity: 0.4;
            cursor: move;
            left: 0;
            top: 0;
        }
        #fdj .fdjBox {
            position: absolute;
            width: 450px;
            height: 450px;
            top: 0;
            left: 460px;
            display: none;
        }
    </style>
</head>
<body>
<!--这里是大图片-->
<div id="fdj">
    <img src="image/img.jpg">
        <div class="mengban"></div>
    <div class="fdjBox"></div>
</div>
<script>
    <!-- onload能保证图片也加载完毕 -->
    window.onload = function() {
        let fdj = document.getElementById('fdj');
        let mengban = fdj.getElementsByClassName('mengban')[0];
        let fdjBox = fdj.getElementsByClassName('fdjBox')[0];
        //图片尺寸
        let imgWidth = fdj.getElementsByTagName('img')[0].width;
        fdj.onmousemove = function(event) {
            //这里获取了蒙板的left和top(offsetLeft是fdj距离视口的位置)
            let left = event.clientX - this.offsetLeft - imgWidth / 2 / 2;
            let top = event.clientY - this.offsetTop - imgWidth / 2 / 2;
            //console.log(left + ',' + top);
            if (left < 0) {
                left = 0;
            }
            if (left > this.offsetWidth - imgWidth/2) {
                left = this.offsetWidth - imgWidth/2;
            }
            if (top < 0) {
                top = 0;
            }
            if (top > this.offsetHeight - imgWidth/2) {
                top = this.offsetHeight - imgWidth/2;
            }
            mengban.style.left = left + 'px';
            mengban.style.top = top + 'px';
            mengban.style.display = 'block';
            fdjBox.style.backgroundImage = 'url(image/img.jpg)';
            fdjBox.style.backgroundRepeat = 'no-repeat';
            fdjBox.style.backgroundPosition = -left * 2 + 'px' + ' ' + -top * 2 + 'px';
            fdjBox.style.display = 'block';
        }
        fdj.onmouseout = function() {
            mengban.style.display = 'none';
            fdjBox.style.display = 'none';
        }
    }
</script>
</body>
</html>